package chapter04

/**
 *
 * @author cdhuangchao3
 * @date 2023/6/4 4:54 PM
 */
object Test02_ForLoop {
  def main(args: Array[String]): Unit = {
    for (i <- 1 to 9)
      print(i)
    for (i <- 1.to(9))
      print(i)
    for (i <- Range(1, 10))
      print(i)
    for (i <- 1 until 10) {
      print(i)
    }
    println("=" * 10)
    // 2.集合遍历
    for (i <- Array(12, 34, 45)) {
      print(i)
    }
    // 3.循环守卫
    println("=" * 10)
    for (i <- 1 to 10 if i % 2 == 0) {
      print(i)
    }
    // 4.循环步长
    println("=" * 10)
    for (i <- (1 to 10).by(2)) {
      print(i)
    }
    for (i <- 1 to 10 reverse) {
      print(i)
    }
    for (i <- 1.0 to 3.0 by 0.5) {
      print(i)
    }
    // 5.循环嵌套
    println("=" * 10)
    for (i <- 1 to 3; j <- 2 to 4) {
      println(s"i=${i};j=${j}")
    }
    for (i <- 1 to 9; j <- 1 to i) {
      print(s"${j} * ${i} = ${i * j}\t")
      if (j == i) println()
    }
    // 6.循环引入变量
    println("=" * 10)
    for (i <- 1 to 3; j = 4 - i) {
      println(s"i=${i};j=${j}")
    }
    for {
      i <- 1 to 3
      j = 4 - i} {
      println(s"i=${i};j=${j}")
    }
    // 7.循环返回值
    val a = for (i <- 1 to 3) {
      i
    }
    println("a="+a)
    val b = for (i <- 1 to 3) yield i
    println("b="+b)
  }

}
